package com.linmo.questionmatcher;

import com.linmo.historymanage.HistoryManage;
import com.linmo.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QuestionMatcher {

    private static final Logger log = LoggerFactory.getLogger(QuestionMatcher.class);
    private HistoryManage historyManage = new HistoryManage();
    private List<String> questionTemplates;//问题模板缓存

    public QuestionMatcher() {
        loadQuestionTemplates();
    }

    // 加载问题模板
    public void loadQuestionTemplates() {
        log.info("加载问题模板");
        questionTemplates = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT question FROM questions";
            Statement statement = conn.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            questionTemplates.clear();

            while (resultSet.next()) {
                String question = resultSet.getString("question");
                questionTemplates.add(question);
                //String answer = resultSet.getString("answer");
                //questionTemplates.put(question, answer);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //匹配问题并返回回答
    public String matchResponse(int currentSessionId,String inputQuestion) {
        double maxSimilarity = 0.0;
        String maxMatched = null;
        //保存用户输入消息
        historyManage.saveMessage(currentSessionId, "User", inputQuestion);

        //System.out.println(questionTemplates);//test遍历

        for (String question : questionTemplates) {
            double similarity = calculateCombinedSimilarity(inputQuestion, question);
            if (similarity > maxSimilarity) {
                maxSimilarity = similarity;
                maxMatched = question;
            }
        }
        if (maxSimilarity >= 0.6) {
            //String answer = questionTemplates.get(maxMatched);
            //historyManage.saveHistory(1, inputQuestion, answer);

            try (Connection conn = DBUtil.getConnection()){
                String sql = "SELECT answer FROM questions WHERE question = ?";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, maxMatched);
                ResultSet rs = pstmt.executeQuery();

                if (rs.next()) {
                    String answer = rs.getString("answer");
                    historyManage.saveMessage(currentSessionId, "Linmo", answer);
                    return answer;
                }

                return "我不太明白你的问题哦";

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        } else {
            historyManage.saveMessage(currentSessionId, "Linmo", "我不太明白你的问题哦。");
            return "我不太明白你的问题哦。";
        }
    }

    //结合编辑距离和 Jaccard 相似度求综合相似度
    private double calculateCombinedSimilarity(String inputQuestion, String question) {
        // 编辑距离
        int editDistance = LevenshteinDistance.distance(inputQuestion, question);
        double editSimilarity = 1.0 - (double) editDistance / Math.max(inputQuestion.length(), question.length());

        // Jaccard 相似度
        double jaccardSimilarity = JaccardSimilarity.similarity(inputQuestion, question);

        // 综合相似度（可以根据需要调整权重）
        return 0.6 * editSimilarity + 0.4 * jaccardSimilarity;
    }
}

